package com.ming.controller;

import com.ming.VO.ProductInfoVO;
import com.ming.VO.ProductVO;
import com.ming.VO.ResultVO;
import com.ming.pojo.ProductCategory;
import com.ming.pojo.ProductInfo;
import com.ming.service.CategoryService;
import com.ming.service.ProductService;
import com.ming.utils.ResultVoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by LIANG on 2018/3/14.
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @GetMapping("/list")
    public ResultVO list(){
        //1 查询所有的上架的商品
        List<ProductInfo> productInfoList = productService.findUpAll();
        //2 查询类目（一次性查询）
        //传统方法
/*        List<Integer> list1  = new ArrayList<>();
        for (ProductInfo productInfo: list){
            list1.add(productInfo.getCategoryType());
       }*/
        //精简方法（java 1.8）lambda 表达式
        List<Integer> categoryTypeList = productInfoList.stream().map(e ->e.getCategoryType()).collect(Collectors.toList());
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(categoryTypeList);
        //3 数据拼接
        List<ProductVO> productVOList  = new ArrayList<>();
        for (ProductCategory productCategory:productCategoryList){
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo:productInfoList){
                if (productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultVoUtil.success(productVOList);
    }

}
